/*
 * 描述： <描述>
 * 修改人： Weng.weng
 * 修改时间： 2021年10月25日
 * 项目： test
 */
package com.aeasycredit.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <功能简述><br>
 * <功能详细描述>
 * 
 * @author Weng.weng
 * @version [版本号, 2021年10月25日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class TuServer {

	/** 
	 * <功能简述><br>
	 * <功能详细描述>
	 *
	 * @param args
	 * 
	 * @return void [返回类型说明]
	 * @throws [异常类型] [异常说明]
	 * @see [类、类#方法、类#成员]
	 * @version [版本号, 2021年10月25日]
	 * @author Weng.weng
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// 监听指定的端口
	    int port = 26001;
	    ServerSocket server = new ServerSocket(port);
	    // server将一直等待连接的到来
	    System.out.println("server将一直等待连接的到来");
	    
	    char theEndOfRecord = (char)19;

	    //如果使用多线程，那就需要线程池，防止并发过高时创建过多线程耗尽资源
	    ExecutorService threadPool = Executors.newFixedThreadPool(20);
	    
	    while (true) {
	      Socket socket = server.accept();
	      
	      Runnable runnable=()->{
	        try {
//	          // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
//	          InputStream inputStream = socket.getInputStream();
//	          byte[] bytes = new byte[1024];
//	          int len;
//	          StringBuilder sb = new StringBuilder();
//	          while ((len = inputStream.read(bytes)) != -1) {
//	            // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
//	            sb.append(new String(bytes, 0, len, "UTF-8"));
//	          }
//	          System.out.println("get message from client: " + sb);
	          
	          // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
	          InputStream inputStream = socket.getInputStream();
	          BufferedReader read = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
	          String line;
	          StringBuilder sb = new StringBuilder();
	          while ((line = read.readLine()) != null) {
	            //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
	        	  int endIndex = line.indexOf(theEndOfRecord);
	        	  if (endIndex >= 0) {
	        		  sb.append(line.substring(0, endIndex));
	        		  break;
	        	  } else {
	        		  sb.append(line);
	        	  }
	          }
	          System.out.println("get message from client: " + sb);
	          socket.shutdownInput(); // TODO
	          
	          
	          OutputStream outputStream = socket.getOutputStream();
	          outputStream.write("Hello Client,I get the message.\r\n".getBytes("UTF-8"));
	          outputStream.flush();
	          socket.shutdownOutput();
	          
	          inputStream.close();
	          outputStream.close();
	          socket.close();
	        } catch (Exception e) {
	          e.printStackTrace();
	        }
	      };
	      threadPool.submit(runnable);
	    }
		
	}
	
	  public static void main2(String[] args) throws Exception {
		    // 监听指定的端口
		    int port = 26001;
		    ServerSocket server = new ServerSocket(port);
		    
		    // server将一直等待连接的到来
		    System.out.println("server将一直等待连接的到来");
		    Socket socket = server.accept();
		    // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
		    InputStream inputStream = socket.getInputStream();
		    byte[] bytes = new byte[1024];
		    int len;
		    StringBuilder sb = new StringBuilder();
		    //只有当客户端关闭它的输出流的时候，服务端才能取得结尾的-1
		    while ((len = inputStream.read(bytes)) != -1) {
		      // 注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
		      sb.append(new String(bytes, 0, len, "UTF-8"));
		    }
		    System.out.println("get message from client: " + sb);

		    OutputStream outputStream = socket.getOutputStream();
		    outputStream.write("Hello Client,I get the message.".getBytes("UTF-8"));

//		    inputStream.close();
//		    outputStream.close();
//		    socket.close();
//		    server.close();
		  }
	  
	   public static void main5(String[] args) {
		      try {
		         ServerSocket ss = new ServerSocket(26001);
		         System.out.println("启动服务器....");
		         Socket s = ss.accept();
		         System.out.println("客户端:"+s.getInetAddress().getLocalHost()+"已连接到服务器");
		         
		         BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		         //读取客户端发送来的消息
		         String mess = br.readLine();
		         System.out.println("客户端："+mess);
		         
		         //send(s, mess);
		         
		         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		         bw.write(mess+"\n");
		         bw.flush();
		      } catch (IOException e) {
		         e.printStackTrace();
		      }
		   }
	   
	   public static void send(Socket s, String msg) throws IOException {  
//	        for (int i = 0; i < list.size(); i++) {  
//	            Socket groupSocket = list.get(i);  
	            OutputStream out = s.getOutputStream();  
	            DataOutputStream dout = new DataOutputStream(out);  
	            dout.writeUTF(msg + "\r\n");  
	            dout.flush();  
	            out.flush();  
//	        }  
	    } 

}
